#include "ArrayList.h"
#include <stdlib.h>

void initSeqList(SL* sl)
{
	assert(sl);//断言
	if (sl == NULL) {
		return;
	}
	sl->arrayList = NULL;
	sl->capacity = sl->size = 0;
	printf("SeqList init finished \n");
}

void destroySeqList(SL* sl)
{
	assert(sl);//断言
	if (sl->arrayList)//不为空，为真
	{
		free(sl->arrayList);//销毁动态开辟的数组
		sl->arrayList = NULL;
		sl->capacity = sl->size = 0;
	}
	printf("SeqList destroy finished \n");
}
void pushBackSeqList(SL* sl, SLDataType x)
{
	assert(sl);
	if (sl->size == sl->capacity)
	{
		int newCapacity = sl->capacity == 0 ? 4 : sl->capacity * 2;
		SLDataType* newArr = (SLDataType*)realloc(sl->arrayList, newCapacity * sizeof(SLDataType));
		if (newArr == NULL)
		{
			perror("realloc failed!");
			exit(-1);//return;
		}
		sl->arrayList = newArr;
		sl->capacity = newCapacity;
	}
	sl->arrayList[sl->size] = x;
	sl->size++;
}
void pushFontSeqList(SL* sl, SLDataType x)
{
	assert(sl);
	checkCapacitySeqList(sl);
	int end = sl->size - 1;
	while (end >= 0)
	{
		sl->arrayList[end] = sl->arrayList[end + 1];
		--end;
	}
	sl->arrayList[0] = x;
}
void popBackSeqList(SL* sl)
{
	assert(sl);
	if (sl->size == 0)
	{
		return;
	}
	//assert(sl->size > 0); 暴力检查
	sl->size--;
}
void popFontSeqList(SL* sl)
{
	assert(sl);
	if (sl->size == 0) return;  // 防止空表删除
	int end = sl->size - 1;
	for (int i = 0; i < end; i++)
	{
		sl->arrayList[i] = sl->arrayList[i + 1];
	}
	sl->size--;
}
void printSeqList(SL* sl)
{
	assert(sl);
	for (int i = 0; i < sl->size; i++)
	{
		printf("%d num is: %d\n", i + 1, sl->arrayList[i]);
	}
}
void checkCapacitySeqList(SL* sl)
{
	assert(sl);
	if (sl->size == sl->capacity)
	{
		int newCapacity = sl->capacity == 0 ? 4 : sl->capacity * 2;
		SLDataType* newArr = (SLDataType*)realloc(sl->arrayList, newCapacity * sizeof(SLDataType));
		if (newArr == NULL)
		{
			perror("realloc failed!");
			exit(-1);//return;
		}
		sl->arrayList = newArr;
		sl->capacity = newCapacity;
	}

}